package com.example.demo.controller;

import com.example.demo.config.AjaxResult;
import com.example.demo.model.UserInfo;
import com.example.demo.service.ChatService;
import com.example.demo.service.UserService;
import com.example.demo.util.ConstVariable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/chat")
public class ChatController {
    @Autowired
    private ChatService chatService;

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public AjaxResult getChatList(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail("请先登录");
        }
        return AjaxResult.success(chatService.getChatList(userInfo.getId()));
    }

    @GetMapping("/messages/{otherId}")
    public AjaxResult getMessages(@PathVariable Integer otherId, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail("请先登录");
        }
        return AjaxResult.success(chatService.getMessageList(userInfo.getId(), otherId));
    }

    @GetMapping("/user/{userId}")
    public AjaxResult getUserInfo(@PathVariable Integer userId) {
        UserInfo userInfo = userService.getUserById(userId);
        if (userInfo != null) {
            Map<String, Object> data = new HashMap<>();
            data.put("userId", userInfo.getId());
            data.put("userName", userInfo.getNickname());
            data.put("userAvatar", userInfo.getAvatar());
            return AjaxResult.success(data);
        }
        return AjaxResult.fail("用户不存在");
    }

    @PostMapping("/read/{senderId}")
    public AjaxResult markAsRead(@PathVariable Integer senderId, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail("请先登录");
        }
        chatService.markMessagesAsRead(userInfo.getId(), senderId);
        return AjaxResult.success("消息已读");
    }

    @GetMapping("/unread-count")
    public AjaxResult getUnreadCount(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail("请先登录");
        }
        int unreadCount = chatService.getUnreadMessageCount(userInfo.getId());
        return AjaxResult.success(unreadCount);
    }
} 